#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

namespace SocketMoudle
{
    using namespace LogMoudle;
    const static int gbacklog = 16;

    // 模版方法模式
    // 基类套接字，大部分方法都是纯虚方法
    class Socket
    {
    public:
        virtual ~Socket() {}
        virtual void SocketOrDie() = 0;
        virtual void BindOrDie(uint16_t port) = 0;
        virtual void ListenOrDie(int backlog) = 0;
        virtual std::shared_ptr<Socket> Accept(InetAddr *client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &message) = 0;
        virtual int Connect(const std::string &ip, uint16_t port) = 0;
    public:
        void BuildListenSocketMethod(uint16_t port, int backlog = gbacklog) // 建立监听套接字
        {
            SocketOrDie();
            BindOrDie(port);
            ListenOrDie(backlog);
        }
        void BulidTcpClientSocketMethod()
        {
            SocketOrDie();
        }
        // void BulidUdpSocketMethod()
        // {
        //     SocketOrDie();
        //     BindOrDie();
        // }
    };

    const static int defaultsockfd = -1;
    // 子类
    class TcpSocket : public Socket
    {
    public:
        TcpSocket() : _sockfd(defaultsockfd)
        {
        }
        TcpSocket(int fd) : _sockfd(fd)
        {
        }

        ~TcpSocket() {}

        void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(LogLevel::FATAL) << "socket error";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::INFO) << "socket success";
        }

        void BindOrDie(uint16_t port) override
        {
            InetAddr localaddr(port);
            int n = bind(_sockfd, localaddr.NetAddrPtr(), localaddr.NETAddrLen());
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "bind error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind success";
        }

        void ListenOrDie(int backlog) override
        {
            int n = listen(_sockfd, backlog);
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "listen error";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "listen success";
        }
        // 返回基类指针指向子类方法
        std::shared_ptr<Socket> Accept(InetAddr *client) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int fd = ::accept(_sockfd, CONV(peer), &len);
            if (fd < 0)
            {
                LOG(LogLevel::WARNING) << "accept warning ... ";
                return nullptr;
            }
            client->SetAddr(peer); // 设置client端网络地址
            // 返回Tcp套接字, 未来可以直接用对象的方式读取套接字
            return std::make_shared<TcpSocket>(fd);
        }

        // 流式读取，不关心读到了什么
        int Recv(std::string *out) override
        {
            char buffer[4096*2];
            ssize_t n = ::recv(_sockfd, buffer, sizeof(buffer)-1, 0);
            if (n > 0)
            { // 读取成功
                buffer[n] = 0;
                *out += buffer; // 将从内核缓冲区读到的数据直接拼接到上层，不关心读到了什么
            }
            return n;
        }
        // 发送数据
        int Send(const std::string &message) override
        {
            return send(_sockfd, message.c_str(), message.size(), 0);
        }

        void Close()
        {
            if (_sockfd >= 0)
            {
                close(_sockfd);
            }
        }
        // 连接
        int Connect(const std::string &ip, uint16_t port) override
        {
            InetAddr server(ip, port);
            return ::connect(_sockfd, server.NetAddrPtr(), server.NETAddrLen());
        }

    private:
        int _sockfd; // listensockfd or sockfd
    };

    // class UdpSocket : public Socket
    // {
    // };

}
